package net.caixiaomi.info.ui.mine;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;

import net.caixiaomi.info.R;
import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.base.BaseActivity;
import net.caixiaomi.info.helper.AppHelper;
import net.caixiaomi.info.logger.Timber;
import net.caixiaomi.info.model.BaseCallModel;
import net.caixiaomi.info.model.UserInfoModel;
import net.caixiaomi.info.net.RequestService;
import net.caixiaomi.info.net.ResponseCallback;
import net.caixiaomi.info.net.ResponseError;
import net.caixiaomi.info.net.RetrofitManage;
import net.caixiaomi.info.util.ToastUtil;
import net.caixiaomi.info.widgets.DefLoading;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;

public class FixPasswordActivity extends BaseActivity implements TextWatcher {
    @BindView(R.id.original)
    View mOriginalView;
    @BindView(R.id.divider)
    View mOriginalDivider;
    @BindView(R.id.original_pw)
    EditText mOriginalPW;
    @BindView(R.id.new_pw)
    EditText mNewPW;
    @BindView(R.id.ensure_pw)
    EditText mEnsurePW;
    @BindView(R.id.btn_done)
    TextView mBtnDone;

    /**
     * 显示密码
     */
    @OnClick({R.id.view1, R.id.view2, R.id.view3})
    void toVisiblePassword(View view) {
        switch (view.getId()) {
            case R.id.view1:
                setLookPW(view,mOriginalPW);
                break;
            case R.id.view2:
                setLookPW(view,mNewPW);
                break;
            case R.id.view3:
                setLookPW(view,mEnsurePW);
                break;
        }

    }

    @OnClick(R.id.btn_done)
    void toDone() {
        try {
            AppHelper.hideKeyboard(getCurrentFocus());
            String originalPw = mOriginalPW.getText().toString().trim();
            String newPw = mNewPW.getText().toString().trim();
            String ensurePw = mEnsurePW.getText().toString().trim();

            if (mHasSetPW) {
                if (TextUtils.isEmpty(originalPw)) {
                    ToastUtil.s(R.string.C_INPUT_ORIGINAL_PW);
                    return;
                }
            }
            if (TextUtils.isEmpty(newPw)) {
                ToastUtil.s(mHasSetPW ? R.string.C_INPUT_NEW_PW : R.string.C_INPUT_PASS_WORD_HINT);
                return;
            }
            if (TextUtils.isEmpty(ensurePw)) {
                ToastUtil.s(mHasSetPW ? R.string.C_INPUT_ENSURE_PW : R.string.C_INPUT_ENSURE_PW_1);
                return;
            }

            if (!TextUtils.equals(newPw, ensurePw)) {
                ToastUtil.s(R.string.C_TWICE_PW_DIFF);
                return;
            }

            mLoading.show();

            JSONObject params = new JSONObject();
            params.put("oldLoginPass", originalPw);
            params.put("type", mHasSetPW ? "1" : "0");
            params.put("userLoginPass", ensurePw);
            RequestService requestService = RetrofitManage.getInstance().getRequestService();
            Call<BaseCallModel> baseCallModelCall = requestService.setLoginPass(params);
            baseCallModelCall.enqueue(new ResponseCallback<BaseCallModel>(this) {
                @Override
                public void onSuccess(BaseCallModel data) {
                    mLoading.dismiss();
                    ToastUtil.s(data.msg);
                    UserInfoModel userInfo = CommonApp.getUserInfo();
                    userInfo.setHasPass("1");
                    CommonApp.setUserInfo(userInfo);
                    onBackPressed();
                }

                @Override
                public void onFail(ResponseError error) {
                    mLoading.dismiss();
                    if (error.getCode() >= 300000 && error.getCode() <= 310000) {
                        ToastUtil.s(error.getMessage());
                    }
                }

                @Override
                public void onError() {
                    mLoading.dismiss();
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private boolean mHasSetPW;

    @Override
    protected int layout() {
        return R.layout.act_fix_password;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        UserInfoModel userInfo = CommonApp.getUserInfo();
        mHasSetPW = TextUtils.equals(userInfo.getHasPass(), "1");
        mLoading = new DefLoading(this);
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(getString(mHasSetPW ? R.string.C_FIX : R.string.C_SETTING)).append(getString(R.string.C_LOGIN_PW));
        setTitle(stringBuilder);
        super.onCreate(savedInstanceState);
        mOriginalView.setVisibility(mHasSetPW ? View.VISIBLE : View.GONE);
        mOriginalDivider.setVisibility(mHasSetPW ? View.VISIBLE : View.GONE);

        mNewPW.setHint(mHasSetPW ? R.string.C_INPUT_NEW_PW : R.string.C_INPUT_PASS_WORD_HINT);
        mEnsurePW.setHint(mHasSetPW ? R.string.C_INPUT_ENSURE_PW : R.string.C_INPUT_ENSURE_PW_1);
        stringBuilder.setLength(0);
        stringBuilder.append(getString(R.string.C_CONFIRM)).append(getString(mHasSetPW ? R.string.C_FIX : R.string.C_SETTING));
        mBtnDone.setText(stringBuilder);

        mOriginalPW.addTextChangedListener(this);
        mNewPW.addTextChangedListener(this);
        mEnsurePW.addTextChangedListener(this);

    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        Timber.d("beforeTextChanged == " + s.toString());
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String text = s.toString();
        if (!TextUtils.isEmpty(text)) {
            char c = s.charAt(s.length() - 1);
            if (Character.isSpaceChar(c)) {
                s.delete(s.length() - 1, s.length());
            }
        }
    }

    private void setLookPW(View view, EditText editText) {
        String password = editText.getText().toString().trim();
        if (!view.isSelected()) {
            editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        } else {
            editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        }
        editText.setSelection(password.length());
        view.setSelected(!view.isSelected());
    }

}
